var config = null;
var fakeData = null;

var url = window.location.href;
var host = window.location.host;
var vi = game_data.village.id;

var rallyLink = "http://" + host + "/game.php?village=" + vi + "&screen=place";

var coordsReg = /\s*\(?(\d+\|\d+)\)?\s*/i;
var urlReg    = /[\?&]id=([^&#]*)/;

function getPoints() {
	var currentBuildings = game_data.village.buildings;

	var totalPoints = 0;
	for(var id in currentBuildings) {
		var level = currentBuildings[id];
		if(!config.buildings[id] || level == 0) {
			continue;
		}
		var basePoints = config.buildings[id].basePoints;
		var points = Math.round(basePoints * Math.pow(1.2, level - 1));
		totalPoints += points;
		//points of a building = [points of the building at level 1]*1.2^([level of the building] - 1)
	}
	
	return totalPoints;
}

function sendFakes() {
	var minimumPopulation = Math.round(getPoints() / 100);
	
	var mainUnit = troops.main;
	var fillUnit = troops.fill;
	
	var mainUnitPop = config.units[mainUnit].pop;
	var fillUnitPop = config.units[fillUnit].pop;
	
	var minimumFillUnits = 0;
	if(config.fake_limit) {
		minimumFillUnits = Math.ceil((minimumPopulation - mainUnitPop) / fillUnitPop);
	}
	
	var counts = new Object();
	if(mainUnit == fillUnit) {
		counts[mainUnit] = 1 + minimumFillUnits;
	} else {
		counts[mainUnit] = 1;
		counts[fillUnit] = minimumFillUnits;
	}
	
	if(fakeData.index >= fakeData.villages.length) {
		fakeData.index = 0;
	}
	if(setTroops(counts, fakeData.villages[fakeData.index])) {
		++fakeData.index;
		if(fakeData.index == fakeData.startIndex) {
			alert("This is the last village.");
		}
		localStorage.setItem('twFakesLimited'+threadId, JSON.stringify(fakeData));
	} else {
		alert("You don't have enough units to send the fake.");
	}
}

function setTroops(counts, target) {
	var c = target.split("|");
	$("#units_form input[name=x]").val(c[0]);
	$("#units_form input[name=y]").val(c[1]);
	
	var maxUnits = new Object();
	var canSend = true;
	for(var id in counts) {
		maxUnits[id] = eval($("#unit_input_" + id).next().html());
		if(counts[id] > maxUnits[id]) {
			canSend = false;
		}
	}
	
	if(canSend) {
		for(var id in counts) {
			if(counts[id] <= maxUnits[id]) {
				insertUnit($('#unit_input_' + id), counts[id]);
			}
		}
		return true;
	}
	return false;
}


function processForum(data) {
	var ind1 = data.indexOf('[' + 'village_list]');
	var ind2 = data.indexOf('[/' + 'village_list]');
	if (ind1 == -1 || ind2 == -1) {
		alert("The list is not well formatted or none was found on the forum post.");
		return;
	}
	
	var villages = data.substring(ind1 + 10, ind2).split('<br />');
	fakeData.villages = new Array();
	for(var i = 0; i < villages.length; i++) {
		var m = villages[i].match(coordsReg);
		if(m) {
			fakeData.villages.push(m[1]);
		}
	}
	
	var validDate = new Date();
	validDate.setHours(validDate.getHours() + 1);
	fakeData.listValidUntil = validDate.getTime();
	fakeData.startIndex = Math.round(fakeData.villages.length * Math.random());
	fakeData.index = fakeData.startIndex;
	localStorage.setItem('twFakesLimited'+threadId, JSON.stringify(fakeData));
	
	sendFakes();
}

function readForum() {
	var loc = urlReg.exec(url);
	$.get(config.urls.forum, {screen: "view_thread", thread_id: threadId}, processForum);
}

function main() {
	var fakeString = localStorage.getItem('twFakesLimited'+threadId);
	if(fakeString) {
		fakeData = JSON.parse(fakeString);
	} else {
		fakeData = {listValidUntil:0,villages:[],index:-1};
		localStorage.setItem('twFakesLimited'+threadId, JSON.stringify(fakeData));
	}
	
	if (url.indexOf('screen=place') != -1) {
		if(fakeData.listValidUntil < new Date().getTime()) {
			readForum();
		} else {
			sendFakes();
		}
	} else {
		window.location = rallyLink;
	}
}

function loadSettings() {
	config = new Config();
	config.onloaded = function() {
		main();
	};
	config.load();
}

function initSettings() {
	var configString = localStorage.getItem('twConfig');
	if(configString && configString.length > 0) {
		config = JSON.parse(configString);
	}
	if(config == null || !config.time || (new Date().getTime() - config.time) > 1000 * 3600 * 24 * 7 || !config.buildings.main.basePoints) {
		$.getScript(scriptRoot+"settings.js", loadSettings);
	} else {
		main();
	}
}

initSettings();
